#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ****************************************
# Version : V1.0.0
# Author  : CHQQ
# File    : makeFilesInfo.py
# Create  : 2020/7/1 14:27
__author__ = 'CHQQ'

# ****************************************

import os
import sys
import getopt
import hashlib


# 获取脚本文件的当前路径
def self_file_path(f=""):
    # 获取脚本路径
    path = os.path.dirname(sys.argv[0])
    if not os.path.isdir(path):
        path = sys.path[0]
    if os.path.sep != '/':
        path = path.replace('/', os.path.sep)
    if f:
        return os.path.sep.join((path, f))
    else:
        return path

def get_md5_for_file(fname):
    return hashlib.md5(open(fname, 'rb').read()).hexdigest()

########################################################################################################################
class DownFilesDescribe():
    def __init__(self, topDir, desc_file=''):
        self.top_dir = topDir if topDir.endswith(os.path.sep) else topDir+os.path.sep
        if not desc_file:
            desc_file = os.path.sep.join((os.path.dirname(os.path.dirname(self.top_dir)), 'files.list'))
        self.desc_file = desc_file

    def make_file_describe(self, ftarget, topLen, pathDir):
        for root, dirs, files in os.walk(pathDir):
            #print('-----------------\npathDir={}\nroot : {}\nfiles : {}'.format(pathDir, root, files))
            sort_files = sorted(files, key=lambda x:x)
            for f in sort_files:
                fname = os.path.join(root, f)
                md5val = get_md5_for_file(fname)   # hashlib.md5(open(fname, 'rb').read()).hexdigest()
                describe = '{}:{}\n'.format(fname[topLen:], md5val)
                ftarget.write(describe)

    def build_describe(self):
        top_dir = self.top_dir
        with open(self.desc_file, 'w', encoding='utf-8') as f:
            self.make_file_describe(f, len(top_dir), top_dir)
            pass

def MakeDescribe(args):
    if len(args) > 0:
        dstDir = args[0]
    else:
        dstDir = self_file_path('out/MinerTools')
    if len(args) > 1:
        desc_file = args[1]
    else:
        desc_file = ''
    if not os.path.isdir(dstDir):
        print('Not exist : {}'.format(dstDir))
        return 1
    df = DownFilesDescribe(dstDir, desc_file)
    df.build_describe()
    return 0



def DoMain(args):
    return MakeDescribe(args)


class Usage(Exception):
    def __init__(self, msg):
        self.msg = msg


def main(argv=None):
    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "h", ["help"])
            return DoMain(args)
        except getopt.error as msg:
            raise Usage(msg)
            # more code, unchanged
    except Usage as err:
        print(err.msg, file=sys.stderr)
        print("for help use --help", file=sys.stderr)
        return 2


if __name__ == '__main__':
    sys.exit(main())